package com.le.tester.tip.timedtask.scheduledexecutor;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 * createTime：2022/10/13 14:21
 * description：
 */
public class Task implements Runnable {

    private AtomicLong addCount = new AtomicLong(0L);
    //感觉可行
    private final static ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();

    @Override
    public void run() {
        if (addCount.incrementAndGet() > 9) {
            executorService.shutdownNow();
        }

        LocalDateTime start = LocalDateTime.now();
        System.out.println("start time is " + start);

        //业务逻辑
        System.out.println("exec task,count is " + addCount.get());

        //不想使用这个线程的休眠来达到轮询的实现
        //TimeUnit.MILLISECONDS.sleep(timeInterval);

        LocalDateTime end = LocalDateTime.now();
        System.out.println("duration time is " + ChronoUnit.MILLIS.between(start, end));
    }

    public void f1() {
        try {
            executorService.scheduleAtFixedRate(new Task(), 0L, 500, TimeUnit.MILLISECONDS);
        } finally {
            if (addCount.get() > 10) {
                executorService.shutdown();
            }
        }
    }

    public static void main(String[] args) {
        new Task().f1();
    }
}
